<template>
    <div>
        <el-card class="box-card" shadow="hover">
            <div slot="header" class="clearfix">
                <span>采购基本信息</span>
                <div style="float: right;">
                    <el-button size="small" @click="onClose">取 消</el-button>
                    <template v-if="rolesBtn.includes('purchaseSubmitCode')">
                        <el-button size="small" type="primary" @click="onFormSubmit">重新提交劳务购计划审核</el-button>
                    </template>
                </div>
            </div>
            <form-create v-model="form.fApi" :rule="form.rule" :option="form.option"/>
          </el-card>

          <el-card class="box-card" shadow="hover">
            <div slot="header" class="clearfix">
              <span>原驳回劳务</span>
            </div>
            <!-- 物资分类 和 物资列表 -->
            <table class="custom-table" style="margin-bottom:10px;">
                <tr v-for="(item,index) in otherMaterial.historyMaterialInfo" :key="item.id">
                    <td class="tr-title">分类名称</td><td>{{item.name}}</td>
                    <td class="tr-title">分类合计预估价</td><td> {{item.priceTotal}}</td>
                    <td v-if="index===0" :rowspan="otherMaterial.historyMaterialInfo.length">预估总合计：{{historyTotalSumAll}}</td>
                </tr>
            </table>
            <el-table :data="otherMaterial.historyTableData" style="width: 100%;" ref="table3" stripe>
                <el-table-column prop="name" label="劳务分类名称" width="200"></el-table-column>
                <el-table-column prop="applyNum" label="申请数量" width="140"></el-table-column>
                <el-table-column prop="estimatePrice" label="预估价" width="140"></el-table-column>
                <el-table-column prop="purchaseType" label="采购方式" width="150">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.purchaseType === '2'">邀请采购</el-tag>
                        <el-tag v-if="scope.row.purchaseType === '3'">公开采购</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="skuInfo" label="备注"></el-table-column>
                <el-table-column prop="rejectFlag" label="状态" width="80">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.rejectFlag === '0'">未驳回</el-tag>
                        <el-tag v-if="scope.row.rejectFlag === '1'" type="warning">已驳回</el-tag>
                    </template>
                </el-table-column>
            </el-table>
          </el-card>

          <el-card class="box-card" shadow="hover">
            <div slot="header" class="clearfix">
              <span>劳务信息</span>
              <el-form :model="labour" style="float: right;" :inline="true" size="mini">
                <el-form-item label="专业分包">
                     <el-select v-model="labour.major" filterable @change="labourMajorChange" style="width:100%">
                        <el-option v-for="item in labour.majorList" :key="item.id" :value="item.id" :label="item.name"></el-option>
                    </el-select>
                </el-form-item>
                 <el-form-item label="劳务分包">
                     <el-select v-model="labour.subpackage" filterable @change="labourSubpackageChange" style="width:100%">
                        <el-option v-for="item in labour.subpackageList" :key="item.id" :value="item.id" :label="item.name"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            </div>
            <!-- 物资分类 和 物资列表 -->
            <table class="custom-table" style="margin-bottom:10px;">
                <tr v-for="(item,index) in otherMaterial.materialInfo" :key="item.id">
                    <td class="tr-title">分类名称</td><td>{{item.name}}</td>
                    <td class="tr-title">分类合计预估价</td><td> {{item.priceTotal}}</td>
                    <td v-if="index===0" :rowspan="otherMaterial.materialInfo.length">预估合计：{{totalSumAll}}</td>
                </tr>
            </table>
            <el-table :key="keys" :data="otherMaterial.tableData" style="width: 100%;" ref="table2" stripe>
                <el-table-column prop="name" label="劳务分类名称" width="200"></el-table-column>
                <el-table-column prop="applyNum" label="申请数量" width="140">
                    <template slot-scope="scope">
                        <el-input-number v-model="scope.row.applyNum" :disabled="scope.row.rejectFlag === '1'" @change="function(val){return inputPrice(val,scope.row,1)}" :step="1" step-strictly size="mini" :min="1" :max="100000"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column prop="estimatePrice" label="预估价" width="140">
                    <template slot-scope="scope">
                        <el-input-number v-model="scope.row.estimatePrice" :disabled="scope.row.rejectFlag === '1'" @change="function(val){return inputPrice(val,scope.row,2)}" size="mini" :min="1" :max="100000"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column prop="purchaseType" label="采购方式" width="120">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.purchaseType === '2'">邀请采购</el-tag>
                        <el-tag v-if="scope.row.purchaseType === '3'">公开采购</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="rejectFlag" label="状态" width="80">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.rejectFlag === '0'">未驳回</el-tag>
                        <el-tag v-if="scope.row.rejectFlag === '1'" type="warning">已驳回</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="remarks" label="备注" width="280">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.remarks" :disabled="scope.row.rejectFlag === '1'" type="textarea"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150" fixed="right">
                    <template slot-scope="scope">
                        <el-button type="primary" v-if="scope.row.rejectFlag === '1'" size="mini" @click="editOtherMaterial(scope.row)">修改</el-button>
                        <!-- <el-button type="primary" size="mini" @click="addOtherMaterial(scope.row)">新增</el-button> -->
                        <el-button type="danger" size="mini" @click="delOtherMaterial(scope.row,scope.$index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
          </el-card>
          <!--处理人-->
          <el-card class="box-card" shadow="hover">
            <div slot="header" class="clearfix">
              <span>分配转交人</span>
              <el-button style="float: right;" size="small" type="primary" @click="workflowOpen">选择转交人员</el-button>
            </div>
            <el-dialog :title="workflow.title" :visible.sync="workflow.visible" :width="workflow.width" append-to-body :close-on-click-modal="false">
              <el-radio-group v-model="workflow.handleUser">
                  <el-radio v-for="item in workflow.workflowList" :border="true" :key="item.id" :label="item.id">
                   {{item.name}}
                  </el-radio>
              </el-radio-group>
              <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="workflow.visible = false">取 消</el-button>
                <el-button size="small" type="primary" @click="submitWorkflow">保存</el-button>
              </div>
            </el-dialog>
            <el-descriptions border>
              <el-descriptions-item label="转交步骤">内勤评审</el-descriptions-item>
              <el-descriptions-item label="转交人员">{{workflow.applyUser}}</el-descriptions-item>
            </el-descriptions>
          </el-card>
           
    </div>
</template>

<script>
    import store from '@/store'
    import { arrayFormat,formatDate } from "@/utils/index"
    import { 
        FORM_PURCHASE_PLAN,
        OPTION_INLINE,
        OPTION_BLOCK
    } from "@/views/labourPurchase/labourModel/purchase_form"
    import { PARAMS_MATERIAL,LABEL_MATERIAL} from "@/config/common"
  
    import { uploads } from "@/api/common_api"
    import {getLabourList} from "@/api/labour_api"
    import { 
        labourPlanApplyUser,
        getLabourPlanReject,
        labourPlanApplyAgain,
        labourPlanEdit
    } from "@/api/labour_purchase_api"
    export default {
        props: ['row'],
        data() {
            return {
                form:{
                    fApi:{},
                    rule:FORM_PURCHASE_PLAN,
                    option:OPTION_BLOCK
                },
                labour:{
                    major:'',
                    majorList:[],
                    subpackage:'',
                    subpackageList:[]
                },
                annxFileName:'',//临时文件
                //物资统计--  统计列表 ，物资列表
                otherMaterial:{
                    historyTableData:[],
                    historyMaterialInfo:[],
                    materialInfo:[],
                    tableData:[]
                },
                workflow:{
                    title:'选择审核人',
                    width:"600px",
                    visible:false,
                    handleUser:'',//选择审核人
                    applyUser:'',//审核人
                    remarks:'',
                    workflowList:[]
                },
                tis:"",
                keys:0,//用于添加物资时更新列表
                params: {
                    type:"page",
                    pageNum: 1,
                    pageSize: 10
                },
            };
        },
        computed: {
            rolesBtn() {
                return this.$store.getters.permission_user.roles.length >=1 ? this.$store.getters.permission_user.roles[0].permissions:[];
            },
            historyTotalSumAll(){//劳务驳回估计合计
                let totalSumAll = 0;
                this.otherMaterial.historyMaterialInfo.map((item) => {totalSumAll += item.priceTotal})
                return totalSumAll
            },
            totalSumAll(){//劳务分类评估价合计
                let totalSumAll = 0;
                this.otherMaterial.materialInfo.map((item) => {totalSumAll += item.priceTotal})
                return totalSumAll
            }
        },
        mounted(){
            this.getRejectData(this.row.id);
            this.getLabourSubpackageList();
            this.getLabourMajorList();
        },
        methods: {
            //上传pdf
            uploadPdf(){
                this.$refs.pdfFile.click();
            },
            async pdfChange(e){
                e.preventDefault();
                let _this = this;
                let file = e.target.files[0];
                if(file===undefined){return;}
                if (file.name.indexOf('.pdf') === -1) {
                    _this.$message.error("只支持pdf");
                    e.target.value= "";
                    return;
                }
                let formData = new FormData();
                formData.append("resType",file);
                const {code,data} = await uploads('annxPDF',formData);
                if(code === 200){
                    this.annxFileName = data;//临时储存
                    this.form.fApi.setValue({"files":file.name});//传给后端
                    e.target.value = "";
                }
            },
            /**-------------------------------------------劳务相关------------------------------------------------------------------*/           
            //劳务分包
            async getLabourSubpackageList(){
                let params = {};
                params.type = 1;
                params.pageNum = 1;
                params.pageSize=100;
                const {code,data} = await getLabourList(params);
                if(code === 200){
                   this.labour.subpackageList = data.list;
                }
            },
            //专业分包
            async getLabourMajorList(){
                let params = {};
                params.type = 2;
                params.pageNum = 1;
                params.pageSize=100;
                const {code,data} = await getLabourList(params);
                if(code === 200){
                    this.labour.majorList = data.list;
                }
            },
            labourMajorChange(val){
                this.labour.majorList.forEach(item => {
                    if(item.id === val){
                        let listId = this.otherMaterial.tableData.map(v=>v.id);
                        if(!listId.includes(val)){
                            item.labourId = item.id;
                            this.otherMaterial.tableData.push(item);
                        }
                    }
                });
                this.materialClassifyTotal();
            },
            labourSubpackageChange(val){
                this.labour.subpackageList.forEach(item => {
                    if(item.id === val){
                        let listId = this.otherMaterial.tableData.map(v=>v.id);
                        if(!listId.includes(val)){
                            item.labourId = item.id;
                            this.otherMaterial.tableData.push(item);
                        }
                    }
                });
                this.materialClassifyTotal();
            },
            //修改已驳回的物资信息
            editOtherMaterial(row){
                this.$confirm("确认已驳回修改为未驳回", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
                }).then(async () => {
                    row.rejectFlag = '0';
                    const {code,msg} = await labourPlanEdit(row);
                    if(code === 200){
                        //修改驳回成功后 重新更新详情接口
                        this.getRejectData(this.row.id)
                    }
                }).catch(() => {});
            },
            //已驳回的重新渲染
            async getRejectData(id){
                const {code,data} = await getLabourPlanReject(id);
                if(code === 200){
                    //其他赋值
                    this.form.fApi.setValue({
                        "name":this.row.name,
                        "startTime":formatDate(this.row.startTime,true),
                        "budget":this.row.budget,
                        "payType":this.row.payType,
                        "bidContent":this.row.bidContent,
                        "contractingScope":this.row.contractingScope,
                        "contractForm":this.row.contractForm,
                        "qualification":this.row.qualification,
                        "files":this.row.files
                    })

                    //原驳回劳务数据，只渲染已驳回的数据 
                    this.otherMaterial.historyTableData = data.filter(v=>{return v.rejectFlag==='1'});

                    let countMap = {};
                    this.otherMaterial.historyTableData.forEach(item=>{
                        if(!countMap[item.name]){
                            countMap[item.name] = {
                                priceTotal:0,
                                name:item.name
                            }
                        }
                        if(item.applyNum !== undefined && item.estimatePrice !== undefined){//两个值都有
                            if(item.rejectFlag === '1'){//只统计已驳回的
                                let price = item.estimatePrice * item.applyNum;
                                let prices = parseFloat(countMap[item.name].priceTotal) + parseFloat(price);
                                countMap[item.name].priceTotal = (prices+'').indexOf(".") !== -1 ? prices.toFixed(2) : prices;
                            }
                        }
                        let materialInfo = [];
                        for(var p in countMap){
                            materialInfo.push(countMap[p]);
                        }
                        this.otherMaterial.historyMaterialInfo = materialInfo;
                        
                    })
                    //原驳回物资数据，只渲染未驳回的数据   该数据渲染到物资列表中，提交一并
                    this.otherMaterial.tableData = data.filter(v=>{return v.rejectFlag==='0'});
                    this.materialClassifyTotal();
                }
            },
        
         
            //单件合计
            inputPrice(val,row,type){
                if(!val){return;}
                if(!/^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/.test(val)){return;}//只能为数字 小数点两位
                this.materialClassifyTotal();
            },
            materialClassifyTotal(){
                let that = this;
                let countMap = {};
                that.otherMaterial.tableData.forEach(item=>{
                    if(!countMap[item.name]){
                        countMap[item.name] = {
                            priceTotal:0,
                            name:item.name
                        }
                    }
                    if(item.applyNum !== undefined && item.estimatePrice !== undefined){//两个值都有
                        let price = item.estimatePrice * item.applyNum;
                        let prices = parseFloat(countMap[item.name].priceTotal) + parseFloat(price);
                        countMap[item.name].priceTotal = (prices+'').indexOf(".") !== -1 ? prices.toFixed(2) : prices;
                    }
                    let materialInfo = [];
                    for(var p in countMap){
                        materialInfo.push(countMap[p]);
                    }
                    that.otherMaterial.materialInfo = materialInfo;
                    
                })
            },
            //新增物资
            /* addOtherMaterial(row){
                let index = this.otherMaterial.tableData.findIndex(v=>v.id === row.id);
                let params = {
                    id:'',
                    id:row.id,
                    name:row.name,
                    applyNum:undefined,
                    estimatePrice:undefined,
                    remarks:'',
                    add:true,
                    del:true
                }
                this.otherMaterial.tableData.splice(index++,0,params);
                this.keys++;
            }, */
            //删除物资
            delOtherMaterial(row,index){
                this.otherMaterial.tableData.forEach(v=>{
                    if(v.id === row.id){
                        v.applyNum = undefined;
                        v.estimatePrice = undefined;
                        v.remarks = '';
                    }
                })
                this.otherMaterial.tableData.splice(index,1);
                this.materialClassifyTotal();
            },
            //转交人相关操作
            async workflowOpen(){
                const { code,data,msg } = await labourPlanApplyUser(12);
                if(code === 200){
                    this.workflow.handleUser = '';
                    this.workflow.workflowList = data;
                    this.workflow.visible = true;
                }
            },
            submitWorkflow(){
                if(!this.workflow.handleUser){
                    return this.$message.error('请选择转交人员！');
                }
                //匹配处理人
                let user = this.workflow.workflowList.find(v=>v.id === this.workflow.handleUser);
                this.workflow.applyUser = user.name;
                this.workflow.visible = false;
            },
            //提交
            async onFormSubmit(formData) {
                this.form.fApi.submit(async (formData, $f) => {
                    try {
                       
                        if(this.otherMaterial.tableData.length === 0){
                            return this.$message.error('请选择物资！');
                        }
                        const arr = this.otherMaterial.tableData;
                        for(var i=0;i<arr.length;i++){
                            if(arr[i].applyNum === undefined || arr[i].applyNum === ''){
                                return this.$message.error('检测到物资第'+(i+1)+'行申请数量未填写！');
                            }
                            if(arr[i].estimatePrice === undefined || arr[i].estimatePrice === ''){
                                return this.$message.error('检测到物资第'+(i+1)+'行预估价未填写！');
                            }
                        }
                        
                        if(!this.workflow.handleUser){
                            return this.$message.error('请选择转交人员！');
                        }
                        this.otherMaterial.tableData.forEach((v,i)=>{
                            v.id = '';
                            v.sortNum = (i+1);
                        })
                        formData.labourList = this.otherMaterial.tableData;
                        //根据处理人匹配处理人姓名
                        formData.handleUser = this.workflow.handleUser;//处理人id
                        formData.id = this.row.id;
                        const req =  await labourPlanApplyAgain(formData);
                        if (req.code == 200) {
                            this.$message.success('重构采购计划成功！');
                            this.onClose();//关闭弹出框
                            this.loadList();//新增成功后刷新列表
                        }
                    } catch (error) {
                        this.$message.info(JSON.stringify(error));
                    }
                })
            },
            loadList() {
                this.$emit("on-search-click", this.params);
            },
            onClose() {
                this.$emit("on-cancel-click",'formReject');
            }
        }
    };
    </script>
    <style>
        .el-radio{
            margin:10px;
        }
    </style>
    